#ifndef NETLIB_THREADLOCALSINGLETON_H
#define NETLIB_THREADLOCALSINGLETON_H

// 线程本地单例类

#include "noncopyable.h"

#include <assert.h>
#include <pthread.h>

namespace netlib
{

template<typename T>
class ThreadLocalSingleton : noncopyable // 不可拷贝
{
public:
    ThreadLocalSingleton() = delete;
    ~ThreadLocalSingleton() = delete;

    static T& instance() // 返回单例对象引用，如果未创建则创建一份
    {
        if (!t_value_)
        {
            t_value_ = new T();
            deleter_.set(t_value_);
        }
        return *t_value_;
    }

    static T* pointer() { return t_value_; } // 返回单例对象的指针

private:

    static void destructor(void* obj) // 销毁对象，系统注册，自动调用
    {
        assert(obj == t_value_);

        //T_must_be_complete_type防止不完全类型导致崩溃
        typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];
        T_must_be_complete_type dummy; (void) dummy;
        delete t_value_;
        t_value_ = 0;
    }

    class Deleter // 内部内置类
    {
    public:
        Deleter() // 构造初始化线程私有数据，并向系统注册销毁函数
        { pthread_key_create(&pkey_, &ThreadLocalSingleton::destructor); }

        ~Deleter() { pthread_key_delete(pkey_); }

        void set(T* newObj) // 修改线程私有数据
        {
            assert(pthread_getspecific(pkey_) == NULL);
            pthread_setspecific(pkey_, newObj);
        }

        pthread_key_t pkey_;            // 线程私有数据标识

    }; // class Deleter end

    static __thread T* t_value_;        // POD类型 每个线程都有一份，线程私有数据的指针
    static Deleter deleter_;            // 销毁指针所指的对象

}; // class ThreadLocalSingleton end

template<typename T>
__thread T* ThreadLocalSingleton<T>::t_value_ = 0;

template<typename T>
typename ThreadLocalSingleton<T>::Deleter ThreadLocalSingleton<T>::deleter_;

} // namespace netlib end

#endif